// 岗位详情页面初始化
document.addEventListener('DOMContentLoaded', function() {
    console.log('页面加载完成，初始化开始');
    
    // 立即隐藏加载指示器
    hideLoadingSpinner();
    
    // 清除之前设置的任何加载超时处理器
    if (window._loadingTimeout) {
        clearTimeout(window._loadingTimeout);
    }
    
    initInternshipDetail();
    initApplyModal();
    handleImageErrors();
});

// 隐藏加载指示器
function hideLoadingSpinner() {
    const loadingElement = document.querySelector('.loading-spinner');
    if (loadingElement) {
        loadingElement.style.display = 'none';
        loadingElement.classList.remove('show');
    }
}

// 初始化实习岗位详情页
function initInternshipDetail() {
    // 获取URL参数中的实习ID
    const urlParams = new URLSearchParams(window.location.search);
    const internshipId = urlParams.get('id');
    
    if (internshipId) {
        loadInternshipDetail(internshipId);
        loadRelatedJobs();
    } else {
        console.error('未找到实习ID');
        showToast('加载失败，请重试');
    }
    
    // 初始化按钮事件
    initButtonEvents();
    
    // 添加返回按钮事件
    document.querySelector('.back-button').addEventListener('click', function() {
        window.history.back();
    });
    
    // 添加分享按钮事件
    document.querySelector('.share-button').addEventListener('click', function() {
        shareInternship();
    });
    
    // 监听页面滚动以实现吸顶效果
    window.addEventListener('scroll', function() {
        handlePageScroll();
    });
}

// 处理页面滚动
function handlePageScroll() {
    const header = document.querySelector('.job-header');
    const headerHeight = header.offsetHeight;
    const scrollTop = window.scrollY;
    
    if (scrollTop > headerHeight / 2) {
        document.querySelector('.page-header').classList.add('sticky');
        document.querySelector('.page-header .title').textContent = 
            document.querySelector('.job-title h1').textContent;
    } else {
        document.querySelector('.page-header').classList.remove('sticky');
        document.querySelector('.page-header .title').textContent = '实习详情';
    }
}

// 初始化按钮事件
function initButtonEvents() {
    // 申请按钮事件
    const applyBtn = document.querySelector('.apply-btn');
    if (applyBtn) {
        applyBtn.addEventListener('click', function() {
            showApplyModal();
        });
    }
    
    // 收藏按钮事件
    const favoriteBtn = document.querySelector('.favorite-btn');
    if (favoriteBtn) {
        favoriteBtn.addEventListener('click', function() {
            toggleFavorite(this);
        });
    }
    
    // 关闭申请模态框
    const modalCloseBtn = document.querySelector('.modal-close');
    if (modalCloseBtn) {
        modalCloseBtn.addEventListener('click', function() {
            hideApplyModal();
        });
    }
    
    // 点击弹窗外部关闭
    const applyModal = document.querySelector('#apply-modal');
    if (applyModal) {
        applyModal.addEventListener('click', function(e) {
            if (e.target === this) {
                hideApplyModal();
            }
        });
    }
    
    // 提交申请表单
    const applyForm = document.querySelector('.apply-form');
    if (applyForm) {
        applyForm.addEventListener('submit', function(e) {
            e.preventDefault();
            submitApplication();
        });
    }
    
    // 文件上传预览
    const resumeInput = document.querySelector('#resume');
    if (resumeInput) {
        resumeInput.addEventListener('change', function() {
            const fileName = this.files[0]?.name || '';
            const fileNameElement = document.querySelector('.file-name');
            
            if (fileName && fileNameElement) {
                fileNameElement.textContent = fileName;
                fileNameElement.style.display = 'block';
            } else if (fileNameElement) {
                fileNameElement.style.display = 'none';
            }
        });
    }
}

// 加载实习岗位详情数据
function loadInternshipDetail(internshipId) {
    // 不显示加载状态
    // showLoading(true);
    
    // 模拟API请求
    setTimeout(() => {
        // 假设这是从API获取的数据
        const internshipData = {
            id: internshipId,
            title: '前端开发实习生',
            company: '科技互联网公司',
            logo: 'https://source.unsplash.com/random/400x400/?company/1',
            location: '北京市 · 海淀区',
            salary: '300-400元/天',
            duration: '3-6个月',
            workdays: '5天/周',
            education: '本科及以上',
            tags: ['前端开发', 'Vue.js', 'React', 'JavaScript'],
            highlights: [
                '知名互联网企业',
                '弹性工作时间',
                '提供免费午餐',
                '实习转正机会'
            ],
            responsibilities: [
                '参与公司产品的前端开发和维护工作',
                '配合后端工程师完成接口对接',
                '优化网站前端性能，提升用户体验',
                '参与前端技术调研和技术选型',
                '完成导师和上级安排的其他任务'
            ],
            requirements: [
                '计算机相关专业本科及以上学历',
                '熟悉HTML、CSS、JavaScript等前端技术',
                '了解Vue.js、React等主流前端框架',
                '有良好的代码编写习惯和问题解决能力',
                '有责任心、学习能力强、团队协作意识好'
            ],
            benefits: [
                '有竞争力的实习薪资和补贴',
                '灵活的工作时间安排',
                '优秀者可获得正式工作机会',
                '与行业专家共事，快速成长',
                '舒适的办公环境和团队氛围'
            ],
            companyInfo: {
                name: '科技互联网公司',
                industry: '互联网/IT',
                size: '500-2000人',
                founded: '2010年',
                intro: '我们是一家以技术创新为驱动的互联网公司，致力于为用户提供优质的数字化服务解决方案。公司拥有完善的人才培养体系，为员工提供广阔的发展空间和具有竞争力的薪酬福利。',
                culture: '开放、创新、包容、共赢'
            },
            status: 'active',
            postDate: '2023-05-15',
            deadlineDate: '2023-06-30',
            views: 1258,
            applications: 86
        };
        
        // 清除加载超时计时器
        if (window._loadingTimeout) {
            clearTimeout(window._loadingTimeout);
        }
        
        renderInternshipDetail(internshipData);
        
        // 确保加载指示器被隐藏
        hideLoadingSpinner();
    }, 800);
}

// 渲染实习岗位详情数据
function renderInternshipDetail(data) {
    // 设置页面标题
    document.title = `${data.title} - ${data.company}`;
    document.querySelector('.header-title').textContent = data.title;
    
    // 渲染基本信息
    document.querySelector('.job-title').textContent = data.title;
    document.querySelector('.company-logo').src = data.logo;
    document.querySelector('.company-logo').alt = data.company + ' 公司标志';
    document.querySelector('.company-name').textContent = data.company;
    
    // 渲染标签
    const tagsContainer = document.querySelector('.job-tags');
    tagsContainer.innerHTML = '';
    data.tags.forEach(tag => {
        const tagElement = document.createElement('span');
        tagElement.className = 'tag';
        tagElement.textContent = tag;
        tagsContainer.appendChild(tagElement);
    });
    
    // 渲染岗位亮点信息
    document.querySelector('.salary .highlight-text').textContent = data.salary;
    document.querySelector('.location .highlight-text').textContent = data.location;
    document.querySelector('.duration .highlight-text').textContent = data.duration;
    document.querySelector('.education .highlight-text').textContent = data.education;
    
    // 渲染岗位职责
    const responsibilitiesContainer = document.querySelector('.responsibilities');
    responsibilitiesContainer.innerHTML = '';
    data.responsibilities.forEach(item => {
        const paragraph = document.createElement('p');
        paragraph.textContent = item;
        responsibilitiesContainer.appendChild(paragraph);
    });
    
    // 渲染申请要求
    const requirementsContainer = document.querySelector('.requirements');
    requirementsContainer.innerHTML = '';
    data.requirements.forEach(item => {
        const paragraph = document.createElement('p');
        paragraph.textContent = item;
        requirementsContainer.appendChild(paragraph);
    });
    
    // 渲染实习福利
    const benefitsContainer = document.querySelector('.benefits');
    benefitsContainer.innerHTML = '';
    data.benefits.forEach(benefit => {
        const benefitItem = document.createElement('div');
        benefitItem.className = 'benefit-item';
        benefitItem.innerHTML = `
            <i class="iconfont icon-gift"></i>
            <div class="benefit-info">
                <h3>${benefit.title}</h3>
                <p>${benefit.desc}</p>
            </div>
        `;
        benefitsContainer.appendChild(benefitItem);
    });
    
    // 渲染公司信息
    document.querySelector('.company-info p').textContent = data.companyInfo.intro;
    
    // 渲染公司环境图片
    const companyImagesContainer = document.querySelector('.company-images');
    companyImagesContainer.innerHTML = '';
    data.companyInfo.images.forEach(imgSrc => {
        const img = document.createElement('img');
        img.src = imgSrc;
        img.alt = '公司环境';
        companyImagesContainer.appendChild(img);
    });
    
    // 设置职位标题和公司信息
    document.querySelector('.job-title h1').textContent = data.title;
    document.querySelector('.company-name').textContent = data.company;
    document.querySelector('.company-logo').src = data.logo;
    document.querySelector('.company-logo').alt = data.company + ' 公司标志';
    
    // 设置职位基本信息
    document.querySelector('.location span').textContent = data.location;
    document.querySelector('.salary span').textContent = data.salary;
    document.querySelector('.duration span').textContent = data.duration;
    document.querySelector('.workdays span').textContent = data.workdays;
    document.querySelector('.education span').textContent = data.education;
    
    // 渲染亮点
    const highlightsContainer = document.querySelector('.highlights-list');
    highlightsContainer.innerHTML = '';
    data.highlights.forEach(highlight => {
        const li = document.createElement('li');
        li.innerHTML = `<span class="highlight-icon"><i class="fa fa-check-circle"></i></span>${highlight}`;
        highlightsContainer.appendChild(li);
    });
    
    // 设置统计信息
    document.querySelector('.views-count').textContent = data.views;
    document.querySelector('.applications-count').textContent = data.applications;
    
    // 设置发布时间和截止日期
    document.querySelector('.post-date').textContent = formatDate(data.postDate);
    document.querySelector('.deadline-date').textContent = formatDate(data.deadlineDate);
    
    // 根据状态调整申请按钮
    const applyBtn = document.querySelector('.apply-btn');
    if (data.status !== 'active') {
        applyBtn.disabled = true;
        applyBtn.textContent = '已截止';
    }
}

// 加载相关推荐岗位
function loadRelatedJobs() {
    // 模拟API请求
    setTimeout(() => {
        // 假设这是从API获取的相关职位数据
        const relatedJobs = [
            {
                id: '1001',
                title: '后端开发实习生',
                company: '科技互联网公司',
                logo: 'https://source.unsplash.com/random/400x400/?company/2',
                location: '北京市 · 朝阳区',
                salary: '350-450元/天',
                tags: ['Java', 'Spring Boot', '后端开发']
            },
            {
                id: '1002',
                title: 'UI设计实习生',
                company: '创新设计公司',
                logo: 'https://source.unsplash.com/random/400x400/?company/3',
                location: '上海市 · 浦东新区',
                salary: '300-400元/天',
                tags: ['UI设计', 'Figma', 'Sketch']
            },
            {
                id: '1003',
                title: '产品经理实习生',
                company: '互联网教育公司',
                logo: 'https://source.unsplash.com/random/400x400/?company/4',
                location: '深圳市 · 南山区',
                salary: '280-380元/天',
                tags: ['产品设计', '用户研究', '数据分析']
            }
        ];
        
        renderRelatedJobs(relatedJobs);
    }, 1000);
}

// 渲染相关推荐岗位
function renderRelatedJobs(jobs) {
    const container = document.querySelector('.related-jobs');
    container.innerHTML = '';
    
    jobs.forEach(job => {
        const jobCard = createJobCard(job);
        container.appendChild(jobCard);
    });
}

// 创建职位卡片
function createJobCard(job) {
    const card = document.createElement('div');
    card.className = 'job-card';
    card.setAttribute('data-id', job.id);
    
    // 添加波纹效果
    card.addEventListener('click', function(event) {
        createRippleEffect(event, this);
        
        // 跳转到岗位详情页
        setTimeout(() => {
            window.location.href = `internship-detail.html?id=${job.id}`;
        }, 300);
    });
    
    card.innerHTML = `
        <div class="job-card-content">
            <img src="${job.logo}" alt="${job.company}公司" class="company-logo">
            <div class="job-info">
                <h3 class="job-title">${job.title}</h3>
                <p class="company-name">${job.company}</p>
                <div class="job-meta">
                    <span class="salary">${job.salary}</span>
                    <span class="location">${job.location}</span>
                </div>
            </div>
        </div>
        <div class="apply-tag">${job.isHot ? '<span class="hot-tag">热门</span>' : ''}</div>
    `;
    
    return card;
}

// 创建点击涟漪效果
function createRippleEffect(event, element) {
    const ripple = document.createElement('span');
    ripple.className = 'ripple-effect';
    
    const rect = element.getBoundingClientRect();
    const x = event.clientX - rect.left;
    const y = event.clientY - rect.top;
    
    ripple.style.left = x + 'px';
    ripple.style.top = y + 'px';
    
    element.appendChild(ripple);
    
    setTimeout(() => {
        ripple.remove();
    }, 600);
}

// 初始化申请弹窗
function initApplyModal() {
    // 关闭按钮事件
    document.querySelector('.close-btn').addEventListener('click', function() {
        hideApplyModal();
    });
    
    // 点击弹窗外部关闭
    document.querySelector('.apply-modal').addEventListener('click', function(e) {
        if (e.target === this) {
            hideApplyModal();
        }
    });
    
    // 提交申请表单
    document.querySelector('#apply-form').addEventListener('submit', function(e) {
        e.preventDefault();
        submitApplication();
    });
    
    // 文件上传预览
    document.querySelector('#resume').addEventListener('change', function() {
        const fileName = this.files[0]?.name || '';
        const fileNameElement = document.querySelector('.file-name');
        
        if (fileName) {
            fileNameElement.textContent = fileName;
            fileNameElement.style.display = 'block';
        } else {
            fileNameElement.style.display = 'none';
        }
    });
}

// 显示申请弹窗
function showApplyModal() {
    console.log('打开申请模态框');
    const modal = document.querySelector('#apply-modal');
    if (!modal) {
        console.error('找不到申请模态框元素');
        return;
    }
    
    modal.style.display = 'flex';
    modal.classList.add('show');
    document.body.style.overflow = 'hidden';
}

// 隐藏申请弹窗
function hideApplyModal() {
    console.log('关闭申请模态框');
    const modal = document.querySelector('#apply-modal');
    if (!modal) {
        console.error('找不到申请模态框元素');
        return;
    }
    
    modal.style.display = 'none';
    modal.classList.remove('show');
    document.body.style.overflow = '';
}

// 提交申请
function submitApplication() {
    const form = document.querySelector('.apply-form');
    if (!form) {
        console.error('找不到申请表单元素');
        return;
    }
    
    const formData = new FormData(form);
    
    // 表单验证
    const name = form.querySelector('#name').value.trim();
    const phone = form.querySelector('#phone').value.trim();
    const email = form.querySelector('#email').value.trim();
    const school = form.querySelector('#school').value.trim();
    const major = form.querySelector('#major').value.trim();
    const graduation = form.querySelector('#graduation').value;
    
    if (!name || !phone || !email || !school || !major || !graduation) {
        showToast('请填写所有必填信息');
        return;
    }
    
    // 检查邮箱格式
    if (!/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(email)) {
        showToast('请输入有效的邮箱地址');
        return;
    }
    
    // 检查手机号格式
    if (!/^1[3-9]\d{9}$/.test(phone)) {
        showToast('请输入有效的手机号码');
        return;
    }
    
    // 显示提交中状态
    const submitBtn = form.querySelector('button[type="submit"]');
    const originalText = submitBtn.textContent;
    submitBtn.disabled = true;
    submitBtn.textContent = '提交中...';
    
    // 模拟API请求
    setTimeout(() => {
        // 重置表单
        form.reset();
        
        // 重置文件名显示
        const fileNameElement = document.querySelector('.file-name');
        if (fileNameElement) {
            fileNameElement.textContent = '';
            fileNameElement.style.display = 'none';
        }
        
        // 恢复按钮状态
        submitBtn.disabled = false;
        submitBtn.textContent = originalText;
        
        // 隐藏模态框
        hideApplyModal();
        
        // 显示成功消息
        showToast('申请已成功提交，请等待通知');
    }, 1500);
}

// 切换收藏状态
function toggleFavorite(button) {
    button.classList.toggle('active');
    const isFavorite = button.classList.contains('active');
    
    if (isFavorite) {
        button.innerHTML = '<i class="fa fa-heart"></i> 已收藏';
        showToast('已添加到收藏');
    } else {
        button.innerHTML = '<i class="fa fa-heart-o"></i> 收藏';
        showToast('已取消收藏');
    }
}

// 分享实习岗位
function shareInternship() {
    // 获取当前页面URL
    const url = window.location.href;
    const title = document.querySelector('.job-title h1').textContent;
    const company = document.querySelector('.company-name').textContent;
    
    // 模拟分享功能
    if (navigator.share) {
        navigator.share({
            title: `${title} - ${company}`,
            text: `${company}招聘${title}，待遇优厚，推荐查看！`,
            url: url
        })
        .then(() => console.log('分享成功'))
        .catch((error) => console.log('分享失败', error));
    } else {
        // 复制链接到剪贴板
        navigator.clipboard.writeText(url)
            .then(() => {
                showToast('链接已复制，可以分享给朋友了');
            })
            .catch(err => {
                console.error('复制失败：', err);
                showToast('复制链接失败，请手动复制');
            });
    }
}

// 显示加载状态 - 禁用此功能
function showLoading(isLoading) {
    // 不执行任何操作，禁用加载提示
    console.log('showLoading 被调用但已禁用, isLoading:', isLoading);
    return;
}

// 显示提示消息
function showToast(message) {
    const toast = document.createElement('div');
    toast.className = 'toast-message';
    toast.textContent = message;
    
    document.body.appendChild(toast);
    
    // 显示后设置透明度为1实现淡入效果
    setTimeout(() => {
        toast.style.opacity = 1;
    }, 10);
    
    // 3秒后移除
    setTimeout(() => {
        toast.style.opacity = 0;
        
        // 淡出动画完成后移除元素
        setTimeout(() => {
            document.body.removeChild(toast);
        }, 300);
    }, 3000);
}

// 格式化日期
function formatDate(dateString) {
    const date = new Date(dateString);
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    
    return `${year}-${month}-${day}`;
}

// 处理图片加载错误
function handleImageErrors() {
    // 获取所有图片元素
    const images = document.querySelectorAll('img');
    
    // 为每个图片添加错误处理
    images.forEach(img => {
        // 保存原始src
        const originalSrc = img.src;
        
        // 图片加载前的状态
        img.classList.add('loading');
        
        // 确定图片类型与随机ID
        const randomId = Math.floor(Math.random() * 1000);
        let category = 'general';
        
        // 根据图片类的不同分类
        if (img.classList.contains('company-logo')) {
            category = 'company';
        } else if (img.classList.contains('company-banner-img')) {
            category = 'office';
        } else if (img.alt && img.alt.includes('公司环境')) {
            category = 'workplace';
        } else if (img.classList.contains('job-image')) {
            category = 'tech';
        }
        
        // 设置图片优先加载
        img.loading = 'eager';
        
        // 图片加载完成
        img.onload = function() {
            img.classList.remove('loading');
            img.classList.add('loaded');
        };
        
        // 图片加载失败时处理
        img.onerror = function() {
            // 移除加载中状态
            img.classList.remove('loading');
            
            // 根据不同类型设置不同的替代图片
            switch(category) {
                case 'company':
                    img.src = `https://source.unsplash.com/random/400x400/?company,logo,tech/${randomId}`;
                    img.classList.add('company-fallback');
                    break;
                case 'office':
                    img.src = `https://source.unsplash.com/random/1200x400/?office,tech,company/${randomId}`;
                    img.classList.add('banner-fallback');
                    break;
                case 'workplace':
                    img.src = `https://source.unsplash.com/random/800x600/?workplace,office/${randomId}`;
                    break;
                case 'tech':
                    img.src = `https://source.unsplash.com/random/600x400/?technology,coding/${randomId}`;
                    break;
                default:
                    img.src = `https://source.unsplash.com/random/800x600/?business/${randomId}`;
                    break;
            }
            
            // 如果替代图片也失败，使用本地备用图片
            img.onerror = function() {
                if (category === 'company') {
                    img.src = '../img/default-company.png';
                } else if (category === 'office') {
                    img.src = '../img/default-banner.png';
                } else {
                    img.src = '../img/default-image.png';
                }
                img.classList.add('fallback');
            };
        };
    });
} 